package com.qk.management.web.filter;

import cn.hutool.core.util.ObjectUtil;
import com.qk.common.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @author: hm
 * @Date: 2025/10/11 11:40
 * @Description:
 */
@Slf4j
@WebFilter("/*")
@SuppressWarnings("all")
public class LoginCheckFilter implements Filter {

    private static final String LOGIN_URL = "/login";
    private static final String TOKEN_HEADER_NAME = "token";

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        request.getRequestURL();
        if (ObjectUtil.equal(request.getRequestURI(), LOGIN_URL)){
            chain.doFilter(request, response);
            return;
        }
        String token = request.getHeader(TOKEN_HEADER_NAME);
        if (ObjectUtil.isNull(token)){
            response.setStatus(401);
            return;
        }
        try {
            Claims claims = JwtUtils.parseToken(token);
            String username = claims.get("username", String.class);
            log.info("请求用户名: {}", username);
            Object id = claims.get("id");
            log.info("请求用户ID: {}", id);
            chain.doFilter(request, response);
            return;
        } catch (Exception e) {
            log.error("token验证失败: {}", e.getMessage());
            response.setStatus(401);
            return;
        }

    }
}
